# encoding=utf-8

"""IntervalScan.py

    周期扫描的处理接口，执行流程如下:
        1. 第一次回调:
            - 读取数据库，并写入cache
        2. 后续回调:
            - 比对最新的文件列表，如果文件增加了，更新新的部分到数据库
            - 如果和数据库内容比对，文件变少了，说明文件部分丢失，删除数据库中对应的项目
"""
import time
import traceback
import logging
from . import DrScanTools
from . import ScanCache
from DRFileModel import models

loop_count = 1
scan_tools: DrScanTools.DrScanTools = None
scan_cache: ScanCache.ScanCache = None


def interval_first(scan_path: str):
    global scan_cache, scan_tools
    result_list = list(models.DRModel.objects.values_list('file_name', flat=True))
    scan_tools = DrScanTools.DrScanTools(scan_path)
    scan_cache = ScanCache.ScanCache(result_list)


def interval_other():
    global loop_count
    t1 = time.perf_counter()
    new_scan_list = scan_tools.scan_once()
    old_diff, new_diff2 = scan_cache.compare_cache(new_scan_list)

    if len(old_diff) != 0:
        logging.info("next file has missing: {}".format(old_diff))
        for old_name in old_diff:
            old_instance = models.DRModel.objects.filter(file_name=old_name)
            if old_instance.exists():
                old_instance.delete()

    if len(new_diff2) != 0:
        logging.info("new file found: {}".format(new_diff2))
        differ_label = scan_tools.label_list(new_diff2)
        for new_name, label in zip(new_diff2, differ_label):
            models.DRModel.objects.create(file_name=new_name, is_ori=label)
        scan_cache.update_file_cache(new_scan_list)

    t2 = time.perf_counter()
    logging.info("Interval Other Done, loop: {}, time cost: {}s".format(loop_count, t2 - t1))
    loop_count += 1


def interval_job_interface(scan_path: str):
    if scan_cache is None or scan_tools is None:
        interval_first(scan_path)
    else:
        interval_other()


def threading_wrapper(scan_path: str):
    while True:
        try:
            interval_job_interface(scan_path)
        except Exception as e:
            logging.exception(traceback.format_exc())
            print(traceback.format_exc())
        time.sleep(5)
